package com.xbongbong.saas.service.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.opportunityuser.pojo.dto.ClueUserDeleteBatchDTO;
import com.xbongbong.pro.opportunityuser.pojo.vo.ClueUserDeleteBatchVO;
import com.xbongbong.saas.domain.entity.ClueUserEntity;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.service.ClueUserService;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author long
 * @version v1.0
 * @date 2020/11/12 19:01
 * @since v1.0
 */
@Service("clueUserService")
public class ClueUserServiceImpl implements ClueUserService {

    private static final Logger LOG = LoggerFactory.getLogger(ClueUserServiceImpl.class);

    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private UserModel userModel;

    @Override
    public ClueUserDeleteBatchVO deleteBatch(ClueUserDeleteBatchDTO clueUserDeleteBatchDTO) throws XbbException {
        ClueUserDeleteBatchVO clueUserDeleteBatchVO = new ClueUserDeleteBatchVO();
        try {

            List<Long> allowDeleteClueId = clueUserDeleteBatchDTO.getClueIdIn();
            Map<String, Object> param = BeanUtil.convertBean2Map(clueUserDeleteBatchDTO, true);
            param.put("dataIdIn", allowDeleteClueId);
            param.put("del", 0);
            List<ClueUserEntity> clueUserEntities = clueUserModel.findEntitys(param);
            if (Objects.isNull(clueUserEntities)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            if (clueUserEntities.isEmpty()) {
                return clueUserDeleteBatchVO;
            }
            String corpid = clueUserDeleteBatchDTO.getCorpid();
            if (!clueUserEntities.isEmpty()) {
                List<ClueUserEntity> updateClueUserList = new ArrayList<>();
                for (ClueUserEntity item : clueUserEntities) {
                    ClueUserEntity clueUserEntity = new ClueUserEntity();
                    clueUserEntity.setId(item.getId());
                    clueUserEntity.setDataId(item.getDataId());
                    clueUserEntity.setCorpid(corpid);
                    clueUserEntity.setDel(-1);
                    long now = DateUtil.getInt();
                    clueUserEntity.setBackTime(now);
                    clueUserEntity.setUpdateTime(now);
                    clueUserEntity.setDistributionTime(now);
                    updateClueUserList.add(clueUserEntity);
                }
                if (!updateClueUserList.isEmpty()) {
                    clueUserModel.updateBatch(updateClueUserList, corpid);
                }
            }
            
        } catch (Exception e) {
            LOG.error("ClueUserServiceImpl.deteleBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return clueUserDeleteBatchVO;
    }

    @Override
    public void dataConsistencyUpdateUser(String corpid, String userId, String userName, String userAvatar) throws XbbException {
        try {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("userId", userId);
            param.put("del", 0);
            List<ClueUserEntity> clueUserEntities = clueUserModel.findEntitys(param);
            for (ClueUserEntity entity : clueUserEntities) {
                entity.setUserName(userName);
                entity.setUserAvatar(userAvatar);
                clueUserModel.update(entity);
            }
        } catch (Exception e) {
            LOG.error("ClueUserServiceImpl.dataConsistencyUpdateUser 出错，corpid=" + corpid + " userId=" + userId + "  userName=" + userName + "  userAvatar=" + userAvatar, e);
        }
    }

    @Override
    public List<UserEntity> getMainUserList(List<Long> clueIds, String corpid, Integer isMain) {

        if (clueIds == null || clueIds.isEmpty()) {
            return new ArrayList<>();
        }

        List<UserEntity> list = new ArrayList<>();
        Map<String,Object> param = new HashMap<>();
        param.put("dataIdIn", clueIds);
        param.put("corpid", corpid);
        if (isMain != null) {
            param.put("isMain", isMain);
        }
        param.put("del", 0);
        param.put("orderByStr", "is_main desc");
        List<ClueUserEntity> clueUserList = clueUserModel.findEntitys(param);

        List<String> userIdIn = new ArrayList<>();
        for(ClueUserEntity clueUser : clueUserList){
            userIdIn.add(clueUser.getUserId());
        }
        userIdIn.add("-1");
        param.clear();
        param.put("userIdIn", userIdIn);
        param.put("corpid", corpid);
        param.put("del", 0);
        List<UserEntity> userList = userModel.findEntitys(param);

        Map<String, UserEntity> userMap = new HashMap<>();
        for(UserEntity user : userList){
            userMap.put(user.getUserId(), user);
        }

        for(ClueUserEntity clueUser : clueUserList){
            if(userMap.containsKey(clueUser.getUserId())){
                UserEntity userEntity = (UserEntity) CloneUtil.deepClone(userMap.get(clueUser.getUserId()));
                userEntity.setIsMain(clueUser.getIsMain());
                list.add(userEntity);
            }
        }
        List<UserEntity> distinctList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(UserEntity::getUserId))), ArrayList::new));
        return distinctList;
    }
}
